/*
 * HTTP.java
 *
 * Created on 13 de Mar�o de 2007, 14:29
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package Utils;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;

/**
 *
 * @author JAKE
 */
public class HTTP {
    
    /** Creates a new instance of HTTP */
    public HTTP() {
    }
    
    /**
     * Funcao que realiza um pedido HTTP do tipo GET retornando uma String
     * @param request_link String representativa do link para realizar o pedido
     * @throws java.io.IOException 
     * @return Uma String como resposta do Web Service externo ao pedido
     */
    public static String doGetRequestToString(String request_link) throws IOException{
        
        
        //Setting the Proxy
        setProxy();
        
        URL url = new URL(request_link);
        HttpURLConnection http_con = (HttpURLConnection) url.openConnection();
        
        //Setting the authentication
        String encoded = new String(Encode64.base64Encode(new String("i30334:painatal69___").getBytes()));
        http_con.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
        
        //Connection settings
        http_con.setRequestMethod("GET");
        http_con.setDoInput(true);
        http_con.setUseCaches(true);
        
        
        
        //Start the connection
        http_con.connect();
        
        //Get the response code
        int response_code = http_con.getResponseCode();
        
        //Get the Input Stream
        InputStream response_stream = http_con.getInputStream();
        
        //Lets the read the Stream into a Buffer and put it in a String
        String response = getStringFromStream(response_stream);
        
        //finally lets return the response
        return response;
    }
    
    /**
     * Funcao que define a proxy do sistema
     */
    public static void setProxy(){

        Properties systemSettings = System.getProperties();
        systemSettings.put("proxySet","true");
        systemSettings.put("http.proxyHost", "proxy.alunos.di.fc.ul.pt");
        systemSettings.put("http.proxyPort", "3128");
        System.setProperties(systemSettings);
    }
    
    /**
     * Funcao que realiza um pedido HTTP do tipo GET retornando uma InputStream
     * @param request_link String representativa do link para realizar o pedido
     * @throws java.io.IOException 
     * @return Um objecto do tipo InputStream como resposta do Web Service externo ao pedido
     */
    public static InputStream doGetRequest(String request_link) throws IOException{
        
        //Setting the Proxy
        setProxy();
        
        //Setting the connection
        URL url = new URL(request_link);
        HttpURLConnection http_con = (HttpURLConnection) url.openConnection();
        
        //Setting the authentication
        String encoded = new String(Encode64.base64Encode(new String("i30334:painatal69___").getBytes()));
        http_con.setRequestProperty("Proxy-Authorization", "Basic " + encoded); 
       
        
        //Connection setting
        http_con.setRequestMethod("GET");
        http_con.setDoInput(true);
        http_con.setUseCaches(true);
                
        //Start the connection
        http_con.connect();
        
        //Get the response code
        int response_code = http_con.getResponseCode();
        
        //http_con.disconnect();
        
        //Get the Input Stream and return it
        return http_con.getInputStream();
        
    }
    
    
    public static String doPostRequest(String request_link) throws IOException{     
                
        //Setting the Proxy
        setProxy();
        
        URL url = new URL(request_link);
        HttpURLConnection http_con = (HttpURLConnection) url.openConnection();
             
        //Setting the authentication
        String encoded = new String(Encode64.base64Encode(new String("i30334:painatal69___").getBytes()));
        http_con.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
        
        //Connection settings
        http_con.setRequestMethod("POST");
        http_con.setDoInput(true);
        http_con.setUseCaches(true);
        
        //Start the connection
        http_con.connect();
        
        //Get the response code
        int response_code = http_con.getResponseCode();
        
        if(response_code == 411){
            return "ERROR: CODE 411";
        }
        
        //Get the Input Stream
        InputStream response_stream = http_con.getInputStream();
        
        //Lets the read the Stream into a Buffer and put it in a String
        String response = getStringFromStream(response_stream);
        
        //http_con.disconnect();
        
        //finally lets return the response
        return response;
    }
    
    /*
     * send a POST request to Web server
     */
    /**
     * Funcao que realiza um pedido HTTP do tipo POST para realizar o upload de uma foto retornando uma String
     * @param requeststring String representando o que se vai enviar (neste caso fotos).
     * 
     * @param url_link String representado o url para onde se vai enviar a foto
     * @param boundary String de formatacao do pedido
     * @return Uma String como resposta do Web Service externo ao pedido
     */
    public static String sendPostRequest(String requeststring,String url_link,String boundary) {
        //Setting the Proxy
        setProxy();
        
        HttpURLConnection hc = null;
        DataInputStream dis = null;
        DataOutputStream dos = null;
        StringBuffer messagebuffer = new StringBuffer();
        try {
            // Open up an http connection with the Web server
            // for both send and receive operations
            URL url = new URL(url_link);
            hc = (HttpURLConnection) url.openConnection();
            
            //Setting the authentication
            String encoded = new String(Encode64.base64Encode(new String("i30334:painatal69___").getBytes()));
            hc.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
   
            
            //Connection settings
            hc.setRequestMethod("POST");
            hc.setDoInput(true);
            hc.setDoOutput(true);
            
            hc.setUseCaches(true);
            
            //add property for the multipart/form-data Content-Type
            hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            
            // Send the string entered by user byte by byte
            dos = new DataOutputStream(hc.getOutputStream());
            byte[] request_body = requeststring.getBytes();
            for (int i = 0; i < request_body.length; i++) {
                dos.writeByte(request_body[i]);
            }
            
            dos.close();
            
            // Retrieve the response back from the servlet
            messagebuffer.append(hc.getResponseMessage() + "\r\n");
            dis = new DataInputStream(hc.getInputStream());
            int ch;
            // Check the Content-Length first
            long len = hc.getContentLength();
            if(len!=-1) {
                for(int i = 0;i<len;i++) {
                    if((ch = dis.read())!= -1) {
                        messagebuffer.append((char)ch);
                    }
                }
            } else {
                // if the content-length is not available
                while ((ch = dis.read()) != -1)
                    messagebuffer.append((char) ch);
                
            }
            dis.close();
            
        } catch (IOException ioe) {
            messagebuffer = new StringBuffer("[HTTP sendPostRequest] ERROR, IOException");
            
        } finally {
            // Free up i/o streams and http connection
            
            if (hc != null) hc.disconnect();
            
            try {
                if (dis != null) dis.close();
            } catch (IOException ignored) {}
            try {
                if (dos != null) dos.close();
            } catch (IOException ignored) {}
        }
        return messagebuffer.toString();
    }
    
    /**
     * Funcao que converte um objecto do tipo InputStream numa String
     * @param is InputStream a converter
     * @throws java.io.IOException 
     * @return Uma String representado a InputStream convertida
     */
    public static String getStringFromStream(InputStream is) throws IOException{
        String line = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        StringBuffer buffer = new StringBuffer();
        while ((line = in.readLine()) != null) {
            buffer.append(line+'\n');
        }
        return buffer.toString();
    }
    
    
}
